<template>
    <div class="binding zy-content ">
        <!-- 搜索 -->
      <div class="searchBox search-box-layout">
        <Row :gutter="24">
          <Col span="4">
            <div>
              <p class="label">{{$t('员工')}}</p>
              <div class="ipt">
                <Select  v-model="searchParams.empno" filterable clearable :placeholder="`${$t('common.selectInfo')}`" @on-query-change="timeOutgetUserNo">
                    <Option v-for="(item,index) of userNoArr" :value="item.empno" :key="index">{{ item.empno+'-'+item.realname }}</Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button class="search-btn" type="primary" @click="changeNum()" v-has="'watchBindPage'">{{$t('common.Query')}}</Button>
                <Button
                    class="reset-btn"
                    @click="resetSearch()"
                    v-has="'watchBindPage'"
                >{{ $t('common.reset') }}
                </Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>
         <div class="list-layout mt16">
           <!-- 批量删除 批量导出  批量导入 下载模板 新增-->
           <div class="btns clear">
             <span class="title">{{ $t('common.listInformation') }}</span>
             <Button  @click="delFaultCodeShowClick" v-has="'watchBindDelete'">{{$t('common.batchDelete')}}</Button>
             <Button  @click="exportTemplateClick" v-has="'watchBindExport'">{{$t('common.batchExport')}}</Button>
             <Button  @click="createfaultCodeShowH" v-has="'watchBindAdd'">{{$t('common.New')}}</Button>
               <Button @click="getTableColumns(columns)">
                   {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
               </Button>
           </div>
           <!-- 表格 -->
           <div class="tableContent">
             <Table class="resizable-table" border @on-column-width-resize="onColumnWidthResize" :columns="columnsList"  ellipsis ref="selection" stripe :data="dataArr"
                    @on-selection-change="onSelectChange">
               <template slot-scope="{ row ,index}" slot="action">
                    <span class="operationBtn" @click="createfaultCodeShowH(row)" v-has="'watchBindUpdate'"><i class="iconfont zy-common-bianji"></i>{{$t('common.Edit')}}</span>
                 <span class="operationBtn" @click="delPrrShowH(row)" v-has="'watchBindDelete'"><i class="iconfont zy-common-shanchu"></i>{{$t('common.Delete')}}</span>
               </template>
             </Table>
           </div>
           <!-- 分页 -->
           <div class="pageWrap mt16">
             <pageLeftTitle :total="total" :selected="delIds.length"/>
             <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum"
                   @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
           </div>
         </div>
        <!-- 新增编辑 -->
        <Modal :mask-closable="false" v-model="create" :title="addtitle" class="modal-content-layout" width="1000">
            <Form ref="form" class="formList" :model="formItem"  label-position="top" :rules="ruleValidate">
                <Row :gutter="20">
                    <Col span="8">
                        <FormItem :label="$t('部门')">
                            <Select  v-model="formItem.deptId" filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                                <Option v-for="(item,index) of departmentList" :value="item.id" :key="index">{{ item.deptName }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem :label="$t('角色')">
                            <Select  v-model="formItem.roleId" filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                                <Option v-for="(item,index) of roleList" :value="item.id" :key="index">{{ item.name }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem :label="$t('员工工号/姓名')" prop="empno">
                            <Select  v-model="formItem.empno" filterable clearable :placeholder="`${$t('common.selectInfo')}`" @on-query-change="timeOutgetUserNo1">
                                <Option v-for="(item,index) of userArr" :value="item.empno" :key="index">{{ item.empno+'-'+item.realname }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <!-- :label="$t('common.remarks')" -->
                        <FormItem :label="$t('员工姓名')">
                            <Select  v-model="formItem.empno" disabled placeholder="">
                                <Option v-for="(item,index) of userArr" :value="item.empno" :key="index">{{ item.realname }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem :label="$t('员工工号')">
                            <Select  v-model="formItem.empno" disabled placeholder="">
                                <Option v-for="(item,index) of userArr" :value="item.empno" :key="index">{{ item.empno }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem :label="$t('电子邮件')">
                            <Select  v-model="formItem.empno" disabled placeholder="">
                                <Option v-for="(item,index) of userArr" :value="item.empno" :key="index">{{ item.email }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem :label="'DEVEUI'" prop="deveui">
                            <Input type="text" v-model="formItem.deveui" :placeholder="`${$t('common.inputInfo')}`"></Input>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem :label="$t('手表类型')">
                            <Select  v-model="formItem.watchType"  placeholder="">
                                <Option v-for="(item,index) of watchTypes" :value="item.value" :key="index">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem :label="$t('描述')">
                            <Input type="text" v-model="formItem.description" :placeholder="`${$t('common.inputInfo')}`"></Input>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="default" @click="create = false">{{$t('common.Cancle')}}</Button>
                <Button type="primary" :loading="loading" @click="addOk('form')">{{$t('maintenance.Confirmed')}}</Button>
            </div>
        </Modal>
        <!-- 请确认是否删除弹框 -->
        <Modal :mask-closable="false" v-model="delFaultCodeShowF"    :title="$t('common.Delete')" class="modal-title-layout">
          <div class="icon red">
            <i class="iconfont zy-common-shanchu"></i>
          </div>
          <p class="title">
            <span>{{$t('common.confirmDelete')}}</span>
          </p>
            <div slot="footer">
                <Button type="default" @click="delFaultCodeShowF = false">{{$t('common.Cancle')}}</Button>
                <Button type="primary" :loading="loading" @click="deleteOk">{{$t('maintenance.Confirmed')}}</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import { searchApi, addApi, editApi, deleteApi, exportApi } from "@/api/andon/binding/index.js";
import fileDownload from 'js-file-download';
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
    name: "binding",//仓库配置
    components: {},
    mixins:[toggleTableOperation],
    data() {
        return {
            userNoArr:[],
            departmentList:[],
            roleList:[],
            formItem: {},
            addtitle: "",
            allCheck: false,
            loading: false,
            create: false,
            searchParams: {

            },
            watchTypes:[
                {
                    label:this.$t('新表'),
                    value:2
                },
                {
                    label:this.$t('旧表'),
                    value:1
                }
            ],
            pageNum: 1,
            pageSize: 10,
            total: 0,
            columns: [
                {
                    key: 'selection',
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    // title: `部门`,
                    title: `${ this.$t('部门') }`,
                    key: 'department',
                    minWidth: 100,
                    align: 'center',
                    resizable: true
                },
                {
                    // title: `员工工号`,
                    title: `${ this.$t('员工工号') }`,
                    key: 'empno',
                    minWidth: 100,
                    align: 'center',
                    resizable: true
                },
                {
                    // title: `员工姓名`,
                    title: `${ this.$t('员工姓名') }`,
                    key: 'realname',
                    minWidth: 100,
                    align: 'center',
                    resizable: true
                },
                {
                    // title: `Watch IMEI`,
                    title: `DEVEUI`,
                    key: 'deveui',
                    minWidth: 100,
                    align: 'center',
                    resizable: true
                },
                {
                    // title: `Watch IMEI`,
                    title: this.$t('手表类型'),
                    key: 'watchTypeStr',
                    minWidth: 100,
                    align: 'center',
                    resizable: true
                },
                {
                     //title: '操作',
                    title: `${ this.$t('common.operation') }`,
                    slot: "action",
                    fixed: 'right',
                    minWidth: 130,
                    align: "center"
                }
            ],
            dataArr: [],
            delFaultCodeShowF: false,//是否显示删除弹窗
            pageSizeOption: [10, 20, 30, 40],
            delIds: [],
            selection: [],
            ruleValidate: {
                deveui: [
                    { required: true, message: this.$t('common.inputInfo'), trigger: 'blur', }
                ],
                empno: [
                    { required: true, message: this.$t('请选择员工'), trigger: 'blur', }
                ],

                // Description: [
                //     { required: true, message: this.$t('请填写描述'), trigger: 'blur', }
                // ],
            },
            userArr:[],
        }
    },
    created() {
        this.getTableColumnsWidth(this.columns)
    },
    mounted() {
        this.searchList();
        this.getDept()
        this.getRole()
    },
    methods: {
        resetSearch(){
            this.searchParams = {}
            this.searchList()
        },
        getDept() {
            let data = {
                deptName: '',
                pageNo: 1,
                pageSize: 1000,
            };
            this.axios({
                method: 'post',
                url: '/basic/dept/list',
                data
            }).then(res => {
                if (res.code === 200) {
                    this.departmentList = res.data.list
                }
            })
        },
        getRole() {
            let params = {
                pageNum: 1,
                pageSize: 100,
            };
            this.axios({
                method: 'get',
                url: '/basic/role/page',
                params
            }).then(res => {
                if (res.code === 200) {
                    this.roleList = res.data.list
                }
            })
        },
        //延时查询
        timeOutgetUserNo(query){
            clearTimeout(this.timeout);
            let isSearchF =false;
            this.timeout = setTimeout(() => {
                if(query !=""){
                    for(let item of this.userNoArr){
                        if(item.empno==query||item.empno+'-'+item.realname==query||item.realname==query){
                            isSearchF = true
                        }
                    }
                    if(isSearchF==false){
                        this.getUserNo(query);
                    }
                }
            }, 500);
        },
        getUserNo(query){
            this.axios({
                method: 'get',
                url: '/basic/user/searchUser',
                params: {
                    key:query
                }
            }).then(res => {
                if(res.code === 200){
                    this.userNoArr = res.data
                }else{
                    this.$Message.warning(({content:res.msg,duration:6,closable:true}));
                }
            })
        },
        //延时查询
        timeOutgetUserNo1(query){
            clearTimeout(this.timeout);
            let isSearchF =false;
            this.timeout = setTimeout(() => {
                if(query !=""){
                    for(let item of this.userArr){
                        if(item.empno==query||item.empno+'-'+item.realname==query||item.realname==query){
                            isSearchF = true
                        }
                    }
                    if(isSearchF==false){
                        this.getUserNo1(query);
                    }
                }
            }, 500);
        },
        getUserNo1(query){
            return new Promise(resolve => {
                this.axios({
                    method: 'get',
                    url: '/basic/user/findUserDetail',
                    params: {
                        deptId:this.formItem.deptId,
                        roleId:this.formItem.roleId,
                        empno:query
                    }
                }).then(res => {
                    if(res.code === 200){
                        this.userArr = res.data
                    }else{
                        this.$Message.warning(({content:res.msg,duration:6,closable:true}));
                    }
                }).finally(() => {
                    resolve()
                })
            });
        },
        //分页
        changeNum() {
            this.pageNum = 1;
            this.searchList();
        },
        changePageSize(pageSize) {
            this.pageSize = pageSize;
            this.searchList();
        },
        changePageNum(val) {
            this.pageNum = val;
            this.searchList();
        },
        //查询列表
        searchList() {
            let params = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
            };
            for (let key in this.searchParams) {
                if (this.searchParams[key]) {
                    this.$set(params, key, this.searchParams[key])
                }
            }
            searchApi(params).then(res => {
                if (res.code === 200) {
                    this.dataArr = res.data.list
                    this.total = res.data.total
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        //增加或编辑
        async createfaultCodeShowH(row) {
            this.$refs.form.resetFields();
            if (row.id) {
                this.addtitle = `${this.$t('common.Edit')}`
                await this.getUserNo1(row.empno)
                this.formItem = {
                    id:row.id,
                    empno:row.empno,
                    deveui:row.deveui,
                    description:row.description,
                    watchType:row.watchType
                }
            } else {
                this.addtitle = `${this.$t('common.New')}`
                this.formItem = {
                    empno:'',
                    deveui:'',
                    description:''
                };
            }
            this.create = true;
        },
        addOk(name) {
            this.$refs[name].validate((valid) => {
                if (!valid) {
                    return
                } else {
                    this.loading = true;
                    if (this.formItem.id) {
                        editApi(this.formItem).then(res => {
                            this.loading = false;
                            if (res.code === 200) {
                                this.changeNum();
                                this.$Message.success(res.msg);
                                this.create = false;
                            } else {
                                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                            }
                        })
                    } else {
                        addApi(this.formItem).then(res => {
                            this.loading = false;
                            if (res.code === 200) {
                                this.changeNum();
                                this.$Message.success(res.msg);
                                this.create = false;
                            } else {
                                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                            }
                        })
                    }
                }
            })


        },
        //勾选列表
        onSelectChange(selection) {
            let myArray = [];
            selection.map((item, index) => {
                myArray.push(item.id);
            });
            this.delIds = myArray;
            if (selection.length > 0) {
                this.allCheck = true;
            } else {
                this.allCheck = false;
            }
        },
        //批量删除
        delFaultCodeShowClick() {
               if (this.delIds.length == 0) {
                this.$Message.warning({
                    content:`${ this.$t('common.deleteItems') }`,
                    duration: 6,
                    closable: true,
                });
                return;
            } else {
            this.delFaultCodeShowF = true;
            }
        },
        //删除
        delPrrShowH(row) {
            //点击展示提示删除弹窗
            this.delFaultCodeShowF = true;
            this.delIds = [];
            this.delIds.push(row.id);
        },
        deleteOk() {
            this.loading = true;
            let params = { ids: this.delIds }
            deleteApi(params).then(res => {
                this.loading = false;
                if (res.code === 200) {
                    this.changeNum();
                    this.$Message.success(res.msg);
                    this.allCheck = false;
                    this.delFaultCodeShowF = false;
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        //导出
        exportTemplateClick() {
            let params = {};
            for (let key in this.searchParams) {
                if (this.searchParams[key]) {
                    this.$set(params, key, this.searchParams[key])
                }
            }
            const filName = this.$t('员工手表绑定')
            exportApi(params).then(res => {
                fileDownload(res, filName + '.xlsx')
            })
        }
    }
}
</script>

<style lang="scss" scoped>
/deep/.ivu-select-disabled .ivu-select-selection{
    background:#f3f3f3 !important
}

</style>

